package com.fengke.util.file;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import org.apache.log4j.Logger;

import com.fengke.util.Constants;
import com.fengke.util.DateUtil;
import com.fengke.util.LoggerFactory;
import com.fengke.util.MD5Util;

public class FileUtil {
	private static Logger logger = LoggerFactory.getLogger(FileUtil.class);
	/**
	 * 上传图片文件
	 * 返回存储路径
	 * 
	 */
	public static String uploadImageFile(UploadedFile file) {
		String timestamp = DateUtil.formatDate1(new Date());
		String basePath = Constants.UploadFile.UPLOAD_FILE_DIR + timestamp;
		String uploadFileName = MD5Util.getMD5(file.getFileName() + DateUtil.formatFullDate(new Date())) + file.getFileExtension();
		File basePathFile = new File(basePath);
		if (!basePathFile.exists()) {
			basePathFile.mkdirs();
		}
		// 判断同名的文件是否已存在，存在则删除
		File uploadedFile = new File(basePath, uploadFileName);
		if (uploadedFile.exists()) {
			uploadedFile.delete();
		}
		
		// 保存文件
		byte[] buff = new byte[5 * 1024];
		InputStream is = null;
		OutputStream os = null;
		try {
			is = file.getInputStream();
			os = new FileOutputStream(uploadedFile);
			int len = -1;
			
			while((len = is.read(buff)) != -1) {
				os.write(buff, 0, len);
			}
			
			logger.debug("Save file successed! The file path is " + uploadedFile.getPath());
			
		} catch(Exception e) {
			logger.error("Save file failed! The file path is " + uploadedFile.getPath());
		} finally {
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return Constants.UploadFile.RELATIVE_FILE_PATH + timestamp + "/" + uploadFileName;
	}
}
